package com.klm.easymq.demo.controller;

import com.klm.easymq.client.EasyMqClient;
import com.klm.easymq.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息控制器
 * 使用 EasyMqClient 作为统一调用接口
 * @author klm
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private EasyMqClient easyMqClient;

    /**
     * 保存消息
     */
    @PostMapping("/save")
    public Map<String, Object> saveMessage(@RequestBody Message message) {
        Map<String, Object> result = new HashMap<>();
        try {
            message.setCreateTime(LocalDateTime.now());
            // 如果 message 对象中没有 traceId，则生成一个
            if (message.getTraceId() == null || message.getTraceId().isEmpty()) {
                message.setTraceId(java.util.UUID.randomUUID().toString());
            }
            // 如果 message 对象中没有 status，则设置默认状态
            if (message.getStatus() == null || message.getStatus().isEmpty()) {
                message.setStatus("PENDING");
            }
            
            boolean success = easyMqClient.sendMessage(message.getTopic(), message.getContent(), message.getBusinessKey());
            result.put("success", success);
            result.put("message", success ? "消息保存成功" : "消息保存失败");
            result.put("data", message);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "消息保存异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据traceId查询消息
     */
    @GetMapping("/{traceId}")
    public Map<String, Object> getMessage(@PathVariable String traceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Message message = easyMqClient.getMessageByTraceId(traceId);
            result.put("success", true);
            result.put("data", message);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询消息异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询消息
     */
    @GetMapping("/page")
    public Map<String, Object> getMessagePage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String topic,
            @RequestParam(required = false) String status) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            List<Message> messages = easyMqClient.getMessages(topic, status, current, size);
            result.put("success", true);
            result.put("data", messages);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "分页查询异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 更新消息
     */
    @PutMapping("/update")
    public Map<String, Object> updateMessage(@RequestBody Message message) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 通过 EasyMqClient 重新发送消息来更新
            boolean success = easyMqClient.sendMessage(message.getTopic(), message.getContent(), message.getBusinessKey());
            result.put("success", success);
            result.put("message", success ? "消息更新成功" : "消息更新失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "消息更新异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{traceId}")
    public Map<String, Object> deleteMessage(@PathVariable String traceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 标记消息为已处理（软删除）
            easyMqClient.markMessageAsProcessed(traceId, 0);
            result.put("success", true);
            result.put("message", "消息删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "消息删除异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取消息统计信息
     */
    @GetMapping("/stats")
    public Map<String, Object> getMessageStats() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> stats = easyMqClient.getMessageStats();
            result.put("success", true);
            result.put("data", stats);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取统计信息异常: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Map<String, Object> healthCheck() {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean healthy = easyMqClient.isHealthy();
            result.put("success", true);
            result.put("healthy", healthy);
            result.put("message", healthy ? "服务正常" : "服务异常");
        } catch (Exception e) {
            result.put("success", false);
            result.put("healthy", false);
            result.put("message", "健康检查异常: " + e.getMessage());
        }
        return result;
    }
} 